const {
    app,
    Tray,
    Menu,
    dialog
} = require('electron')
const path = require('path')
let mytray

// function createWindow() {
//     const win = new BrowserWindow({
//         width: 800,
//         height: 600,
//         webPreferences: {
//             preload: path.join(__dirname, 'preload.js')
//         }
//     })

//     win.loadFile('index.html')
// }

app.whenReady().then(() => {
    // createWindow()
    createTray()
    // app.on('activate', () => {
    //     if (BrowserWindow.getAllWindows().length === 0) {
    //         createWindow()
    //     }
    // })
})

function createTray() {

    createmyTray({
        icon: path.join(__dirname + "/static/imags/trayicon.png"),
        menuTemplate: [{
                type: 'radio',
                // checked: true,
                label: "start",
                click: () => {
                    if (isTimering()) return
                    startTimer(1000 * 50 * 60)
                }
            },
            {
                type: 'radio',
                label: 'stop',
                checked: true,
                click: () => {
                    stopTimer()
                }
            },
            {
                role: "quit",
            }
        ],
        tip: "定时器",
        title: "timer"
    })
}
// app.on('window-all-closed', () => {
//     if (process.platform !== 'darwin') {
//         app.quit()
//     }
// })
let contextMenu

function createmyTray({
    icon,
    menuTemplate,
    tip,
    title
}) {
    mytray = new Tray(icon)
    contextMenu = Menu.buildFromTemplate(menuTemplate)
    mytray.setContextMenu(contextMenu)
    mytray.setToolTip(tip)
    mytray.setTitle(title)
}

let timerId = null

function startTimer(time) {
    timerId = setTimeout(() => {
        console.log("time over");
        timerId = null
        contextMenu.items[1].checked = true
        dialog.showMessageBox({
            message: "time over!",
            type: "info"
        })
    }, time)
}

function isTimering(params) {
    if (timerId === null) {
        return false
    } else {
        return true
    }
}

function stopTimer(params) {
    clearTimeout(timerId)
    timerId = null
}